import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { HeroSearchService } from '../service/hero-search.service';
import { Hero } from '../Hero/hero';
@Component({
	selector: 'hero-search',
	templateUrl: './hero-search.component.html',
	styleUrls: ['./hero-search.component.css'],
	providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
	heroes: Observable<Hero[]>;
	private searchTerms = new Subject<string>();
	constructor(
		private heroSearchService: HeroSearchService,
		private router: Router) { }
	// 将搜索项推入可观察流。
	search(term: string): void {
		this.searchTerms.next(term);
	}
	ngOnInit(): void {
		this.heroes = this.searchTerms
			.debounceTime(300)        // 等待300ms在每个按键之前考虑术语
			.distinctUntilChanged()   // 忽略下一个搜索项是否与前面相同
			.switchMap(term => term   // 每次更改术语时切换到新的可观察到的
				// 返回可观察到的HTTP搜索
				? this.heroSearchService.search(term)
				//或者没有搜索词的空英雄
				: Observable.of<Hero[]>([]))
			.catch(error => {
				//错误处理
				console.log(error);
				return Observable.of<Hero[]>([]);
			});
	}
	gotoDetail(hero: Hero): void {
		let link = ['/detail', hero.id];
		this.router.navigate(link);
	}
}
